package com.leizhi.demo.monitor.achieve;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @Description RTP 可用端口
 * @Version 1.0.0-SNAPSHOT
 * @Author leizhi
 * @Date 2025/5/16 14:02
 */
public class RtpUsablePort {

    /* 最小范围 */
    private final Integer min;

    /* 最大范围 */
    private final Integer max;

    /* 不可用的端口 */
    private final Set<Integer> unavailable;


    public RtpUsablePort(String radius) {
        String[] ports = radius.split(",");
        this.min = Integer.parseInt(ports[0]);
        this.max = Integer.parseInt(ports[1]);

        int size = (max - min) + 1;
        unavailable = new LinkedHashSet<>(size);
    }

    public Integer usable() {
        for (int i = min; i <= max; i++) {
            if (unavailable.contains(i)) {
                continue;
            }
            unavailable.add(i);
            return i;
        }
        throw new RuntimeException("端口已用完");
    }

    public void remove(Integer port) {
        unavailable.remove(port);
    }

}
